package com.github.yangyishe.p100;

/**
 * 最长公共前缀
 * https://leetcode.cn/problems/longest-common-prefix/
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 *
 *
 *
 * 示例 1：
 *
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 * 示例 2：
 *
 * 输入：strs = ["dog","racecar","car"]
 * 输出：""
 * 解释：输入不存在公共前缀。
 *
 *
 * 提示：
 *
 * 1 <= strs.length <= 200
 * 0 <= strs[i].length <= 200
 * strs[i] 仅由小写英文字母组成
 */
public class Problem14 {
    public static void main(String[] args) {
        Problem14 problem14 = new Problem14();
        String[] params=new String[]{"dog","racecar","car"};
        String result = problem14.longestCommonPrefix(params);
        System.out.println("result:"+result);
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs.length==1) {
            return strs[0];
        }
        String preStr=strs[0];
        for (int i = 1; i < strs.length; i++) {
            if (preStr.length()==0) {
                return "";
            }
            String nextStr = strs[i];
            preStr=calcCommonPrefix(preStr,nextStr);
        }
        return preStr;
    }

    public String calcCommonPrefix(String s1,String s2){
        if (s1.length()==0||s2.length()==0) {
            return "";
        }
        char[] cs1 = s1.toCharArray();
        char[] cs2 = s2.toCharArray();
        int minLen = Math.min(cs1.length, cs2.length);

        int sameLength=minLen;
        for (int i = 0; i < minLen; i++) {
            if (cs1[i]!=cs2[i]) {
                sameLength=i;
                break;
            }
        }
        if (sameLength==0) {
            return "";
        }

        char[] scs=new char[sameLength];
        System.arraycopy(cs1, 0, scs, 0, sameLength);

        return new String(scs);
    }
}
